<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="省/市/自治区" prop="province" label-width="100">
        <el-select v-model="queryParams.province" placeholder="请选择省份/市/自治区" clearable @change="handleProvinceChange">
          <el-option
              v-for="province in provinces"
              :key="province.locationId"
              :label="province.locationName"
              :value="province.locationId"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="所处城市" prop="city">
        <el-select v-model="queryParams.city" placeholder="请选择城市" clearable @change="handleCityChange" :disabled="!queryParams.province">
          <el-option
              v-for="city in cities"
              :key="city.locationId"
              :label="city.locationName"
              :value="city.locationId"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="所处区域" prop="area">
        <el-select v-model="queryParams.area" placeholder="请选择区域" clearable :disabled="!queryParams.city">
          <el-option
              v-for="area in areas"
              :key="area.locationId"
              :label="area.locationName"
              :value="area.locationId"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['apartment:flats:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['apartment:flats:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['apartment:flats:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['apartment:flats:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="flatsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="50" align="center" prop="flatsId" />
      <el-table-column label="公寓名称" align="center" prop="flatsName" />
      <el-table-column label="详细地址" align="center" prop="detail" width="200"/>
      <el-table-column label="空闲房间数" align="center" prop="emptyRoom" />
      <el-table-column label="房间总数" align="center" prop="roomCount" />
      <el-table-column label="省/市/自治区" align="center" prop="provinceName" />
      <el-table-column label="所处城市" align="center" prop="cityName" />
      <el-table-column label="所处区域" align="center" prop="areaName" />
      <el-table-column label="联系方式" align="center" prop="flatsPhoneNumber" width="120"/>
      <el-table-column label="入住状态" align="center" prop="flatsType">
        <template #default="scope">
          <dict-tag :options="apartment_flats_type" :value="scope.row.flatsType"/>
        </template>
      </el-table-column>
      <el-table-column label="公寓状态" align="center" prop="flatsStatus" width="100">
        <template #default="scope">
          <el-switch
              v-model="scope.row.flatsStatus"
              active-value="0"
              inactive-value="1"
              active-text="正常"
              inactive-text="停用"
              @change="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template #default="scope" >
          <el-button link type="primary" @click="handleViewDetails(scope.row)" >查看详情</el-button>
          <el-button link type="primary"  @click="handleUpdate(scope.row)" v-hasPermi="['apartment:flats:edit']">修改</el-button>
          <el-button link type="primary" @click="handleDelete(scope.row)" v-hasPermi="['apartment:flats:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改公寓管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="flatsRef" :model="form" :rules="rules" label-width="100px">
        <!-- ... other form items ... -->
        <el-form-item label="公寓名称" prop="flatsName">
          <el-input v-model="form.flatsName" placeholder="请输入公寓名称" />
        </el-form-item>
        <el-form-item label="公寓电话" prop="flatsPhoneNumber">
          <el-input
              v-model="form.flatsPhoneNumber"
              placeholder="请输入公寓电话"
              maxlength="11"
              show-word-limit
              @input="handlePhoneInput"
          />
        </el-form-item>
        <el-form-item label="省/市/自治区" prop="province">
          <el-select v-model="form.province" placeholder="请选择省份/市/自治区" clearable @change="handleProvinceChangeForm">
            <el-option
                v-for="province in provinces"
                :key="province.locationId"
                :label="province.locationName"
                :value="province.locationId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="所处城市" prop="city">
          <el-select v-model="form.city" placeholder="请选择城市" clearable @change="handleCityChangeForm" :disabled="!form.province">
            <el-option
                v-for="city in cities"
                :key="city.locationId"
                :label="city.locationName"
                :value="city.locationId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="所处区域" prop="area">
          <el-select v-model="form.area" placeholder="请选择区域" clearable :disabled="!form.city">
            <el-option
                v-for="area in areas"
                :key="area.locationId"
                :label="area.locationName"
                :value="area.locationId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="详细地址"  prop="detail" >
          <el-input v-model="form.detail" placeholder="请输入详细地址" />
        </el-form-item>
        <el-form-item label="公寓图片">
          <image-upload v-model="form.flatsImagePath"/>
        </el-form-item>
        <el-form-item label="公寓属性" prop="flatsProperty">
          <el-checkbox-group v-model="form.flatsProperty">
            <el-checkbox
                v-for="data in flatsproperties"
                :key="data.propertyDataId"
                :label="data.propertyDataValue"
            >
              {{data.propertyDataValue}}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>


    <!-- 公寓详情对话框 -->
    <el-dialog title="公寓详情" v-model="detailsOpen" width="600px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="公寓名称">{{ detailsForm.flatsName }}</el-descriptions-item>
        <el-descriptions-item label="公寓电话">{{ detailsForm.flatsPhoneNumber }}</el-descriptions-item>
        <el-descriptions-item label="省/市/自治区">{{ detailsForm.provinceName }}</el-descriptions-item>
        <el-descriptions-item label="所处城市">{{ detailsForm.cityName }}</el-descriptions-item>
        <el-descriptions-item label="所处区域">{{ detailsForm.areaName }}</el-descriptions-item>
        <el-descriptions-item label="详细地址">{{ detailsForm.detail }}</el-descriptions-item>
        <el-descriptions-item label="入住状态">
          <dict-tag :options="apartment_flats_type" :value="detailsForm.flatsType"/>
        </el-descriptions-item>
        <el-descriptions-item label="空闲房间数">{{ detailsForm.emptyRoom }}</el-descriptions-item>
        <el-descriptions-item label="房间总数">{{ detailsForm.roomCount }}</el-descriptions-item>
        <el-descriptions-item label="公寓属性" >
          <el-tag v-for="property in detailsForm.flatsProperty" :key="property" style="margin-right: 5px;">
            {{ property }}
          </el-tag>
        </el-descriptions-item>
        
        <el-descriptions-item label="公寓图片" :span="2">
        <el-carousel v-if="detailsForm.flatsImagePath" :interval="4000" type="card" height="300px">
          <el-carousel-item v-for="(image, index) in detailsForm.flatsImagePath.split(',')" :key="index">
            <el-image :src="image" style="width: 100%; height: 100%; object-fit: cover;" />
          </el-carousel-item>
        </el-carousel>
      </el-descriptions-item>

      </el-descriptions>



    </el-dialog>


  </div>
</template>


<script setup name="Flats">
import { listFlats, getFlats, delFlats, addFlats, updateFlats } from "@/api/apartment/flats";
import { ref, reactive, toRefs, getCurrentInstance } from "vue";
import { listProvince,listCity,listArea } from "@/api/apartment/location";
import {findData} from "@/api/apartment/data.js"


const { proxy } = getCurrentInstance();
const { apartment_flats_type} = proxy.useDict('apartment_flats_type');
const flatsList = ref([]);
const flatsproperties = ref([])
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const provinces = ref([]);
const cities = ref([]);
const areas = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    flatsName: null,
    flatsPhoneNumber: null,
    locationId: null,
    province: null,
    flatsStatus: "0",
    detail: null,
    city: null,
    area: null,
    flatsImagePath: null,
    flatsProperty: null,
    flatsType: null
  },
  rules: {
    flatsName: [
      { required: true, message: "公寓名称不能为空", trigger: "blur" }
    ],
    flatsPhoneNumber: [
      { required: true, message: "公寓电话不能为空", trigger: "blur" },
        {
          pattern: /^1[3456789]\d{9}$/,
          message: "请输入正确的手机号码",
          trigger: "blur"
        }
    ],
    province: [
      { required: true, message: "省份/市/自治区不能为空", trigger: "blur" }
    ],
    city: [
      { required: true, message: "城市不能为空", trigger: "blur" }
    ],
    area: [
      { required: true, message: "区域不能为空", trigger: "blur" }
    ],
    detail: [
      { required: true, message: "详细地址不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

const handlePhoneInput = (value) => {
  // 移除所有非数字字符，并确保长度不超过11位
  const cleanedValue = value.replace(/\D/g, '').slice(0, 11);
  form.value.flatsPhoneNumber = cleanedValue;
};
function getPropertyList() {
  loading.value = true;
  findData(queryParams.value).then(response => {
    flatsproperties.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

function getProvinceList() {
  loading.value = true;
  listProvince().then(response => {
    provinces.value = response.rows;
    loading.value = false;
  });
}
function handleStatusChange(row) {
  let text = row.flatsStatus === "0" ? "启用" : "停用";
  proxy.$modal.confirm('确认要"' + text + '""' + row.flatsName + '"公寓吗？').then(function() {
    return updateFlats({ flatsId: row.flatsId, flatsStatus: row.flatsStatus });
  }).then(() => {
    proxy.$modal.msgSuccess(text + "成功");
    getList();  // 刷新列表
  }).catch(function() {
    row.flatsStatus = row.flatsStatus === "0" ? "1" : "0";
  });
}
function getCityList(provinceId) {
  loading.value = true;
  listCity(provinceId).then(response => {
    cities.value = response.rows;
    loading.value = false;
    proxy.$forceUpdate();
  }).catch(error => {
    console.error("Error fetching cities:", error);
    loading.value = false;
  });
}

function getAreaList(cityId) {
  loading.value = true;
  listArea(cityId).then(response => {
    areas.value = response.rows;
    loading.value = false;
  });
}

function handleProvinceChange(value) {
  console.log("Province changed:", value);
  queryParams.value.city = null;
  queryParams.value.area = null;
  cities.value = [];
  areas.value = [];
  if (value) {
    getCityList(value);
  }
}

function handleCityChange(value) {
  queryParams.value.area = null;
  areas.value = [];
  if (value) {
    getAreaList(value);
  }
}

function handleProvinceChangeForm(value) {
  form.value.city = null;
  form.value.area = null;
  cities.value = [];
  areas.value = [];
  if (value) {
    getCityList(value);
  }
}

function handleCityChangeForm(value) {
  form.value.area = null;
  areas.value = [];
  if (value) {
    getAreaList(value);
  }
}


/** 查询公寓管理列表 */
function getList() {
  loading.value = true;
  listFlats(queryParams.value).then(response => {
    flatsList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  }).catch(error => {
    console.error("Error fetching flats:", error);
    loading.value = false;
  });
}
// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    flatsId: null,
    flatsName: null,
    flatsPhoneNumber: null,
    locationId: null,
    province: null,
    flatsStatus: "0",
    detail: null,
    city: null,
    area: null,
    flatsImagePath: null,
    roomCount: null,
    emptyRoom: null,
    flatsProperty: [],
    flatsType: null
  };
  proxy.resetForm("flatsRef");
  cities.value = [];
  areas.value = [];
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value.pageNum = 1;
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.flatsId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加公寓管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _flatsId = row.flatsId || ids.value
  getFlats(_flatsId).then(response => {
    form.value = response.data;
    if (form.value.province) {
      getCityList(form.value.province);
    }
    if (form.value.city) {
      getAreaList(form.value.city);
    }
    open.value = true;
    title.value = "修改公寓管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["flatsRef"].validate(valid => {
    if (valid) {
      const phoneRegex = /^1[3-9]\d{9}$/;
      if (!phoneRegex.test(form.value.flatsPhoneNumber)) {
        proxy.$modal.msgError("请输入有效的11位手机号码");
        return;
      }
      if (form.value.flatsId != null) {
        updateFlats(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addFlats(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _flatsIds = row.flatsId || ids.value;
  proxy.$modal.confirm('是否确认删除公寓管理编号为"' + _flatsIds + '"的数据项？').then(function() {
    return delFlats(_flatsIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('apartment/flats/export', {
    ...queryParams.value
  }, `flats_${new Date().getTime()}.xlsx`)
}

const detailsOpen = ref(false);
const detailsForm = ref({});

// ... existing code ...

/** 查看详情按钮操作 */
function handleViewDetails(row) {
  getFlats(row.flatsId).then(response => {
    detailsForm.value = response.data;
    detailsOpen.value = true;
  });
}
// 初始化
getList();
getProvinceList();
getPropertyList();
</script>
